package com.keyware.kd.utils;

import io.netty.channel.ConnectTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;

public class HttpClientUtil {

    private static final int CONNECT_TIMEOUT = 5000;
    private static final int SOCKET_TIMEOUT = 10000;

    public static String doGet(String baseUrl) throws UnsupportedEncodingException {
        // 1. 创建HttpClient实例
        HttpClient httpClient = new DefaultHttpClient();
        String responseStr = null;
        // 3. 创建HttpGet请求
        HttpGet httpGet = new HttpGet(baseUrl);
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();
        try {
          //  String cookie ="";
         //   httpGet.addHeader("Cookie", cookie);
            // 4. 执行请求
            HttpResponse response = null;
            httpGet.setConfig(config);
            response = httpClient.execute(httpGet);

            // 5. 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
        //    System.out.println("Status Code: " + statusCode);

            // 6. 处理响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseStr = EntityUtils.toString(entity);
            }
        }  catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 7. 释放连接
            httpClient.getConnectionManager().shutdown();
        }
        return responseStr;
    }

}
